package cn.com.dashihui.api.controller;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.core.Const;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.CacheHolder;
import cn.com.dashihui.api.common.CacheKey;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.PayCode;
import cn.com.dashihui.api.common.ResultField;
import cn.com.dashihui.api.common.ResultMap;
import cn.com.dashihui.api.common.ResultState;
import cn.com.dashihui.api.common.SysConfig;
import cn.com.dashihui.api.common.UserCode;
import cn.com.dashihui.api.dao.Bank;
import cn.com.dashihui.api.dao.Card;
import cn.com.dashihui.api.dao.History;
import cn.com.dashihui.api.dao.OrderG;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.OrderZ;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.dao.UserAddress;
import cn.com.dashihui.api.dao.UserCollection;
import cn.com.dashihui.api.interceptor.AuthClientTokenInterceptor;
import cn.com.dashihui.api.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.api.interceptor.POST;
import cn.com.dashihui.api.service.UserService;
import cn.com.dashihui.kit.CommonKit;

import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.DoubleKit;

import cn.com.dashihui.kit.FTPClientKit;
import cn.com.dashihui.kit.SMSKit;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.pay.SQ.SQpay;
import cn.com.dashihui.pay.ZY.EncryUtils;
import cn.com.dashihui.pay.ZY.ZYPay;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 用户操作对象<br/>包括登录、注册、个人信息管理、重置密码、收藏管理、收货地址管理操作
 * v1.3.1版本，新增加服务端接口按版本号管理，2016-01-25
 */
@Before(AuthLoginInterceptor.class)
public class UserController extends BaseController{
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private UserService service = Duang.duang(UserService.class);
    
    /**
     * 注册时，生成并发送N位短信验证码
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
     * @return CONTENT 生成并发送的N位短信验证码
     */
	@Clear(AuthLoginInterceptor.class)
    public void sendRegCode(){
    	String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	if(StrKit.isBlank(clientid)){
    		renderFailed("参数SIGNATURE不能为空");
    		return;
    	}else if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(service.findByPhone(msisdn)!=null){
    		renderResult(ResultState.STATE_USERNAME_EXISTS,"手机号已经存在，请直接登录");
    		return;
    	}
    	String randomNum = null;
    	String key = CacheHolder.key(CacheKey.CACHE_REGIST_SMS_VALID_CODE_KEY,clientid,msisdn);
    	//判断缓存中是否已经存在未过期的验证码
    	Object oldNum = CacheHolder.get(key);
		if(oldNum!=null){
			//如果有，则继续使用
			randomNum = String.valueOf(oldNum);
		}else{
			//否则生成新的验证码
			randomNum = CommonKit.randomNum();
		}
		if(SMSKit.sendRegCode(msisdn, randomNum)){
			CacheHolder.cache(key, randomNum, CacheHolder.TIME_FIVE_MINUTE);
			Prop debug = new Prop("realtime.properties",Const.DEFAULT_ENCODING);
			if(debug.getBoolean("debug.sms")){
				//短信接口调试模式时，将短信验证码返回给客户端
				renderSuccess(ResultMap.newInstance().put("CODE",randomNum));
				return;
			}else{
				renderSuccess();
				return;
			}
		}
		renderFailed("验证码发送失败，请重新获取");
    }
	
	/**
	 * 用户注册
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 * @param PASSWORD 密码
	 * @param CODE 短信验证码
	 * @return TOKEN 用户签名，在用户登录成功时生成
	 */
	@Clear(AuthLoginInterceptor.class)
    public void regist(){
    	String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String password = getPara("PASSWORD");
    	String code = getPara("CODE");
    	int inviteid = Integer.valueOf(getPara("INVITEID"));
    	
    	//验证各参数
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(!ValidateKit.Mobile(msisdn)){
    		renderFailed("参数PHONE格式不正确");
    		return;
    	}else if(service.findByPhone(msisdn)!=null){
    		renderResult(ResultState.STATE_USERNAME_EXISTS,"手机号已经存在，不能重复注册");
    		return;
    	}else if(StrKit.isBlank(password)){
    		renderFailed("参数PASSWORD不能为空");
    		return;
    	}else if(ValidateKit.Password_reg(password)){
    		renderFailed("密码只能填写数字、字母、下划线组合");
    		return;
    	}else if(password.length()<6||password.length()>18){
    		renderFailed("请保持密码长度在6-18之间");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("参数CODE不能为空");
    		return;
    	}
    	//验证短信验证码
    	String cacheKey = CacheHolder.key(CacheKey.CACHE_REGIST_SMS_VALID_CODE_KEY,clientid,msisdn);
    	if(!CacheHolder.has(cacheKey)){
    		renderFailed("未获取短信验证码或验证码已超时，请重新获取");
    		return;
    	}else if(!CacheHolder.getStr(cacheKey).equals(code)){
    		renderFailed("验证码不正确");
    		return;
    	}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
    	//新建
    	User user = new User()
    			.set("name", msisdn)
    			.set("phone", msisdn)
    			.set("createDate",new Date())
    			.set("password", CommonKit.encryptPassword(password))
    			.set("paypassword", CommonKit.encryptPassword(msisdn.substring(msisdn.length()-6)))
    			.set("card", DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS").substring(2))
    			.set("babythday", new Date());
    	if(inviteid!=0){
    		User inviteUser = service.findUserByInviteid(inviteid);
    		int BossThreeid = inviteUser.getInt("toBossThreeId");
    		if(BossThreeid == 0){
    			BossThreeid = 1;
    		}
    		System.out.println(">>>>>>>>>>>>>>>>"+BossThreeid);
    		int BossOneid = 0;
    		if(inviteUser.getInt("toBossOneId")!=null){
    			BossOneid = inviteUser.getInt("toBossOneId");
    		}
    		
    		System.out.println(">>>>>>>>>>>>>>>>"+BossOneid);
    		
    		int BossTwoid = 0;
    		if(inviteUser.getInt("toBossTwoId")!=null){
    			BossTwoid = inviteUser.getInt("toBossTwoId");
    		}
    		System.out.println(">>>>>>>>>>>>>>>>"+BossTwoid);
    		user.set("toBossThreeId", BossThreeid)
    			.set("toBossTwoId", BossTwoid)
    			.set("toBossOneId", BossOneid)
    			.set("inviteid", inviteid);
    	}
    	//保存用户信息
    	if(service.save(user)){
    		//查询注册奖励
    		Double regSpoint=0.00;
    		Double regJkpoint=0.00;
    		try {
    			regSpoint = SysConfig.getRegSpoint();//获取注册赠送积分
    			regJkpoint=SysConfig.getRegJkpoint();//获取注册赠送抵扣券
    		} catch (Exception e) {
    			renderFailed("查询注册奖励失败");
    		}
    		//奖励新用户财富信息并记录表
			String orderNumStore1 = "ZC"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
			Record re1 = new Record();
			User user2=service.findByPhone(msisdn);
			re1.set("userid", user2.getInt("id"))
			.set("type",1)
			.set("flag",7)
			.set("fromOrderNum",orderNumStore1)
			.set("data",1)
			.set("describe","注册奖励");
			try {
				service.updateValue(user2,regSpoint,regJkpoint,0.00,0.00,0.00,re1,1);
			} catch (Exception e1) {
//				renderFailed("新用户注册操作财富日志表失败");
				renderFailed("网络繁忙...，请稍后重试");
				return;
			}
			
    		//邀请人奖励
    		if(inviteid!=0){
    			Double Spoint = 0.00;
    			try {
    				Spoint = SysConfig.getInviteSpoint();
    				
    			} catch (Exception e) {
    				renderFailed("查询邀请人奖励失败");
    				return;
    			}
    			String orderNumStore = "YQ"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
    			User users = service.findUserByInviteid(inviteid);
    			//奖励用户积分信息    记录表
    			Record re = new Record();
    			re.set("userid", inviteid)
    			.set("type",1)
    			.set("flag",6)
    			.set("fromOrderNum",orderNumStore)
    			.set("type",1)
    			.set("data",1)
    			.set("describe","邀请奖励");
    			int count = 0;
				try {
					count = service.updateSpoint(users,Spoint,re);
				} catch (Exception e) {
//					e.printStackTrace();
//					renderFailed("更改表失败");
					renderFailed("网络繁忙...，请稍后重试");
    				return;
				}
    			
    		}
    		
    		//保存成功后，创建用户与Client之间的session，即登录操作
    		String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
			if(service.login(sessionid, user.getInt("id"), clientid)){
				//登录成功后，将sessionid返回
	    		renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(user.getInt("id"))));
			}else{
				renderSuccess();
			}
			return;
    	}
    	renderFailed("注册失败");
    }
    
    /**
	 * 用户登录
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 * @param PASSWORD 密码
	 * @return TOKEN 用户签名，在用户登录成功时生成
	 */
	@Clear(AuthLoginInterceptor.class)
    public void login(){
    	String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String password = getPara("PASSWORD");
    	//验证各参数
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(!ValidateKit.Mobile(msisdn)){
    		renderFailed("参数PHONE格式不是");
    		return;
    	}else if(StrKit.isBlank(password)){
    		renderFailed("参数PASSWORD不能为空");
    		return;
    	}else if(ValidateKit.Password_reg(password)){
    		renderFailed("密码只能填写数字、字母、下划线组合");
    		return;
    	}else if(password.length()<6||password.length()>18){
    		renderFailed("请保持密码长度在6-18之间");
    		return;
    	}
    	//查询指定手机号用户
    	User user = service.findByPhone(msisdn);
    	if(user == null){
    		renderFailed("用户名不存在，请先注册");
    		return;
    	}
    	System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+password);
    	System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>"+CommonKit.passwordsMatch(password, user.getStr("password")));
    	if(user==null||!CommonKit.passwordsMatch(password, user.getStr("password"))){
    		renderFailed("用户名或登录密码错误");
    		return;
    	}
    	
		//创建用户与Client之间的session，即登录操作
		String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
		if(service.login(sessionid, user.getInt("id"), clientid)){
			//登录成功后，将sessionid返回
    		renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(user.getInt("id"))));
    		return;
		}
		renderFailed("登录失败");
    }
	
	/**
	 * 查询当前登录用户对象的个人信息
	 */
	public void info(){
		//在AuthLoginInterceptor已经判断过当前登录情况，并已经查询了最新用户信息，在此只需要转而输出即可
		renderSuccess(service.findUserInfoById(getCurrentUser().getInt("id")));
	}
	
	/**
	 * 查询当前登录用户各状态信息<br/>
	 * 分别统计“收藏商品数量”、“待付款”、“待发货”、“待收货”、服务订单“待付款”、服务订单“待服务”六种状态的订单数量 
	 * @param APIVERSION 服务端接口版本号，以此判断来兼容旧版本接口
	 * @param STOREID 店铺ID，V1.3.1以后用
	 */
	public void state(){
		String apiVersion = getPara("APIVERSION");
		if(apiVersion.equals(PropKit.get("api.version.131"))){
			//1.3.1版本新增代码，2016-01-26
			String storeidStr = getPara("STOREID");
			if(StrKit.isBlank(storeidStr)){
	    		renderFailed("参数STOREID不能为空");
	    		return;
			}
			Record state = service.getUserState_v131(Integer.valueOf(storeidStr),getCurrentUser().getInt("id"));
			renderSuccess(ResultMap.newInstance()
					.put("COLLECTED",state.get("state1"))
					.put("NOPAY",state.get("state2"))
					.put("WAITDELIVER",state.get("state3"))
					.put("NOTAKE",state.get("state4"))
					.put("SERNOPAY",state.get("state5"))
					.put("SERNOSERVICE",state.get("state6")));
		}else if(apiVersion.equals(PropKit.get("api.version.132"))||apiVersion.equals(PropKit.get("api.version.133"))){
			//1.3.2版本新增代码，2016-03-16
			String storeidStr = getPara("STOREID");
			if(StrKit.isBlank(storeidStr)){
	    		renderFailed("参数STOREID不能为空");
	    		return;
			}
			Record state = service.getUserState_v132(Integer.valueOf(storeidStr),getCurrentUser().getInt("id"));
			renderSuccess(ResultMap.newInstance()
					.put("COLLECTED",state.get("state1"))
					.put("NOPAY",state.get("state2"))
					.put("NOTAKE",state.get("state3"))
					.put("NOEVAL",state.get("state4"))
					.put("SERNOPAY",state.get("state5"))
					.put("SERNOSERVICE",state.get("state6")));
		}
		return;
	}
    
	/**
	 * 我的钱包<br/>
	 * 查询用户的实惠币金额
	 */
	public void money(){
		User user = service.findUserInfoById(getCurrentUser().getInt("id"));
		Record record = service.findInviteUserCount(getCurrentUser().getInt("id"));
		renderSuccess(ResultMap.newInstance()
				.put("INVITECOUNT", record.get("inviteCount"))
				.put("MONEY",user.getDouble("MONEY")).getAttrs());
	}
	
	/**
	 * 登陆以后修改密码
	 */
	public void restPwd(){
		String pwd = getPara("PWD");
		String newPwd = getPara("NEWPWD");
		if(StrKit.isBlank(pwd)){
    		renderFailed("密码不能为空");
    		return;
    	}else if(StrKit.isBlank(newPwd)){
    		renderFailed("新密码不能为空");
    		return;
    	}
		User user = getCurrentUser();
		if(user==null||!CommonKit.passwordsMatch(pwd, user.getStr("password"))){
			renderFailed("旧密码错误");
			return;
		}
		if(service.updatePwdByUsername(CommonKit.encryptPassword(newPwd), user.getStr("phone"))){
			renderSuccess();
		}else{
			renderFailed("重置密码失败");
		}
	}
	
	
	
	/**
	 * 会员奖励规则页面<br/>
	 * 不要求登录，任何人可看
	 */
	@Clear(AuthLoginInterceptor.class)
	public void rule(){
		try {
			setAttr("level2Line", SysConfig.getLevel2Line());
		} catch (Exception e) {
			e.printStackTrace();
		}
		render("rule.jsp");
	}
	
	/**
	 * 会员分享页面<br/>
	 * 只有黄金会员可看，同时还要展示会员的邀请码
	 */
	public void share(){
		setAttr("currentUser", getAttr(PropKit.get("constants.currentUserKey")));
		render("share.jsp");
	}
	
	/**
	 * 找回密码时发送手机验证码
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 */
	@Clear(AuthLoginInterceptor.class)
    public void sendResetPwdCode(){
    	String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("手机号不能为空");
    		return;
    	}else if(service.findByPhone(msisdn)==null){
    		renderFailed("手机号码未注册");
    		return;
    	}
    	String randomNum = null;
    	//判断缓存中是否已经存在未过期的验证码
    	Object oldNum = CacheHolder.get(CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn));
		if(oldNum!=null){
			//如果有，则继续使用
			randomNum = String.valueOf(oldNum);
		}else{
			//否则生成新的验证码
			randomNum = CommonKit.randomNum();
		}
		if(SMSKit.sendFindPwdCode(msisdn, randomNum)){
			CacheHolder.cache(CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn), randomNum, CacheHolder.TIME_FIVE_MINUTE);
			Prop debug = new Prop("realtime.properties",Const.DEFAULT_ENCODING);
			if(debug.getBoolean("debug.sms")){
				//短信接口调试模式时，将短信验证码返回给客户端
				renderSuccess(ResultMap.newInstance().put("CODE",randomNum));
				return;
			}else{
				renderSuccess();
				return;
			}
		}
		renderFailed("验证码发送失败，请重新获取");
    }

	/**
	 * 重置密码
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 * @param CODE 验证码
	 * @param PWD 新密码
	 * @param VERIFYPWD 确认密码
	 */
	@Clear(AuthLoginInterceptor.class)
	public void resetPwd(){
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String code = getPara("CODE");
    	String pwd = getPara("PWD");
    	String verifypwd = getPara("VERIFYPWD");
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("手机号不能为空");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("验证码不能为空");
    		return;
    	}else if(service.findByPhone(msisdn)==null){
    		renderFailed("手机号未注册");
    		return;
    	}else if(StrKit.isBlank(pwd)){
    		renderFailed("密码为空");
    		return;
    	}else if(ValidateKit.Password_reg(pwd)){
    		renderFailed("密码只能填写数字、字母、下划线组合");
    		return;
    	}else if(pwd.length()<6||pwd.length()>18){
    		renderFailed("请保持密码长度在6-18之间");
    		return;
    	}else if(StrKit.isBlank(verifypwd)){
    		renderFailed("确认密码为空");
    		return;
    	}else if(!pwd.equals(verifypwd)){
    		renderFailed("两次密码输入不一致");
    		return;
    	}
		String cacheKey = CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn);
		if(!CacheHolder.has(cacheKey)){
			renderFailed("未获取短信验证码或验证码已超时，请重新获取");
			return;
		}else if(!CacheHolder.getStr(cacheKey).equals(code)){
			renderFailed("验证码不正确");
			return;
		}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
		if(service.updatePwdByUsername(CommonKit.encryptPassword(pwd), msisdn)){
			renderSuccess();
		}else{
			renderFailed("重置密码失败");
		}
	}
	/**
	 * 重置支付密码(本地)
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 * @param CODE 验证码
	 * @param PWD 新密码
	 * @param VERIFYPWD 确认密码
	 */
	@Clear(AuthLoginInterceptor.class)
	public void resetPayPwd1(){
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String code = getPara("CODE");
    	String pwd = getPara("PWD");
    	String verifypwd = getPara("VERIFYPWD");
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("手机号不能为空");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("验证码不能为空");
    		return;
    	}else if(service.findByPhone(msisdn)==null){
    		renderFailed("手机号未注册");
    		return;
    	}else if(StrKit.isBlank(pwd)){
    		renderFailed("密码为空");
    		return;
    	}else if(ValidateKit.Password_reg(pwd)){
    		renderFailed("密码只能填写数字、字母、下划线组合");
    		return;
    	}else if(pwd.length()<6||pwd.length()>18){
    		renderFailed("请保持密码长度在6-18之间");
    		return;
    	}else if(StrKit.isBlank(verifypwd)){
    		renderFailed("确认密码为空");
    		return;
    	}else if(!pwd.equals(verifypwd)){
    		renderFailed("两次密码输入不一致");
    		return;
    	}
		String cacheKey = CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn);
		if(!CacheHolder.has(cacheKey)){
			renderFailed("未获取短信验证码或验证码已超时，请重新获取");
			return;
		}else if(!CacheHolder.getStr(cacheKey).equals(code)){
			renderFailed("验证码不正确");
			return;
		}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
		if(service.updatePayPwdByUsername(CommonKit.encryptPassword(pwd), msisdn)){
			renderSuccess();
		}else{
			renderFailed("重置支付密码失败");
		}
	}
	/**
	 * 换绑手机---认证原手机
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 * @param CODE 验证码
	 */
	public void checkPhone(){
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String code = getPara("CODE");
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("参数CODE不能为空");
    		return;
    	}
    	User user = service.findByPhone(msisdn);
    	if(user==null){
    		renderFailed("手机号未注册");
    		return;
    	}
    	if(user.getInt("id")!=getCurrentUser().getInt("id")){
    		renderFailed("手机号不正确");
    		return;
    	}
		String cacheKey = CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn);
		if(!CacheHolder.has(cacheKey)){
			renderFailed("未获取短信验证码或验证码已超时，请重新获取");
			return;
		}else if(!CacheHolder.getStr(cacheKey).equals(code)){
			renderFailed("验证码不正确");
			return;
		}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
		renderSuccess(1);
	}
	/**
	 * 换绑手机
     * @param SIGNATURE 设备识别码
     * @param TOKEN 签名
	 * @param PHONE 手机号码
	 * @param CODE 验证码
	 */
	public void resetPhone(){
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String code = getPara("NEWCODE");
    	String pwd = getPara("PWD");
    	if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("参数NEWCODE不能为空");
    		return;
    	}else if(service.findByPhone(msisdn)!=null){
    		renderFailed("手机号已注册");
    		return;
    	}else if(StrKit.isBlank(pwd)){
    		renderFailed("密码不能为空");
    		return;
    	}
		String cacheKey = CacheHolder.key(CacheKey.CACHE_RESETPWD_SMS_VALID_CODE_KEY,clientid,msisdn);
		if(!CacheHolder.has(cacheKey)){
			renderFailed("未获取短信验证码或验证码已超时，请重新获取");
			return;
		}else if(!CacheHolder.getStr(cacheKey).equals(code)){
			renderFailed("验证码不正确");
			return;
		}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
	
    	renderSuccess(1);
	}
	
	/**
	 * 头像上传
	 */
	@Before(POST.class)
	@Clear(AuthLoginInterceptor.class)
	public void fileUpload2(){
		
		System.out.println("进入头像上传:");
		UploadFile dat  = getFile("data");
		System.out.println("1");
		if(dat!=null){
			String thumbFileName = null;
			String dir = DirKit.getDir(DirKit.PERSON_LOGO);
			System.out.println("2");
			try {
				thumbFileName = uploadToFtp(dir,dat);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			System.out.println("3："+thumbFileName);
			renderSuccess(dir.concat(thumbFileName));
		}else{
			renderFailed("上传失败");
		}
		
	}
	/**
	 * 更新用户个人信息，可单独修改任一字段或全部修改
	 * @param NICKNAME 昵称
	 * @param SEX 性别
	 * @param AVATOR 头像
	 * @param COMMUNITYID 社区ID
	 * @param BUILDID 楼号ID
	 * @param UNITID 单元号ID
	 * @param FLOORID 楼层ID
	 * @param ROOMID 房间号ID
	 */
	public void update(){
		String name = getPara("NICKNAME");
		String sex = getPara("SEX");
		String avator = getPara("AVATOR");
		String birthday = getPara("BIRTHDAY");
		String city = getPara("CITY");
		String job = getPara("JOB");
		String introduce = getPara("INTRODUCE");
		String loveCate = getPara("LOVECATE");
		User user = getCurrentUser();boolean isNeedUpdate = false;boolean isUpdateAvator = false;
		String avatorOld = user.getStr("avator");
		if(!StrKit.isBlank(name)){
			user.set("name", name);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(sex)&&(sex.equals("1")||sex.equals("2"))){
			user.set("sex", sex);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(avator)){
			user.set("avator", avator);isNeedUpdate = true;isUpdateAvator = true;
		}
		if(!StrKit.isBlank(birthday)){
			user.set("birthday", birthday);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(city)){
			user.set("city", city);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(job)){
			user.set("job", job);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(introduce)){
			user.set("introduce", introduce);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(loveCate)){
			user.set("loveCate", loveCate);isNeedUpdate = true;
		}
		if(isNeedUpdate){
			if(service.update(user)){
				//如果修改用户头像，则需要将旧头像图片删除
				if(isUpdateAvator&&StrKit.isBlank(avatorOld)){
					try {
						FTPClientKit.deleteFile(avatorOld);
					} catch (IOException e) {
						error("用户【"+user.getStr("username")+"】修改头像时，旧头像文件【"+avatorOld+"】删除失败");
						e.printStackTrace();
					}
				}
				renderSuccess();
			}else{
				renderFailed("更新信息失败");
			}
		}else{
			renderSuccess();
		}
	}
	
	/**
	 * 完善用户银行信息，可单独修改任一字段或全部修改
	 */
	public void updatebank() {
		String custName= getPara("CUSTNAME");//获取持卡人姓名
		String cardIdNo=getPara("CARDIDNO");//获取身份证号
		String cardNo=getPara("CARDNO");//获取银行卡号
		String bankNoId=getPara("BANKNOID");//获取银行编码
		String address=getPara("ADDRESS");//获取详细地址
		String email=getPara("EMAIL");//获取邮箱
		//查询用户信息
		User user = getCurrentUser();boolean isNeedUpdate = false;
		//设置用户信息
		if(!StrKit.isBlank(custName)){
			user.set("custName", custName);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(cardIdNo)){
			user.set("cardIdNo", cardIdNo);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(cardNo)){
			user.set("cardNo", cardNo);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(bankNoId)){
			user.set("bankNoId", bankNoId);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(address)){
			user.set("address", address);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(email)){
			user.set("email", email);isNeedUpdate = true;
		}
		//更新用户
		if(isNeedUpdate){
			if(service.update(user)){
				renderSuccess();
			}else{
				renderFailed("完善信息失败");
			}
		}else{
			renderSuccess();
		}
	}
	/**
	 * 完善用户信息
	 */
	public void updateUser() {
		String custName= getPara("CUSTNAME");//获取持卡人姓名
		String cardIdNo=getPara("CARDIDNO");//获取身份证号
		//查询用户信息
		User user = getCurrentUser();boolean isNeedUpdate = false;
		//设置用户信息
		if(!StrKit.isBlank(custName)){
			user.set("custName", custName);isNeedUpdate = true;
		}
		if(!StrKit.isBlank(cardIdNo)){
			user.set("cardIdNo", cardIdNo);isNeedUpdate = true;
		}
		//更新用户
		if(isNeedUpdate){
			if(service.update(user)){
				renderSuccess();
			}else{
				renderFailed("完善信息失败");
			}
		}else{
			renderSuccess();
		}
	}
	/**
	 * 根据银行编号查询银行名称
	 */
	public void queryBankNameByid() {
		 String bankId= getPara("BANKID");//获取银行编码
		 //查询名称
		 if (!StrKit.isBlank(bankId)&&!"null".equals(bankId)) {
			 Record rec = service.queryBankNameByid(Integer.valueOf(bankId));
			 if(rec!=null){
				 renderSuccess(rec);
			 }else{
				 renderFailed("网络繁忙...，请稍后重试");
			 }
		}else {
			renderFailed("网络繁忙...，请稍后重试");
		}
		
	}
	
	/**
	 * 用户收藏指定商品
	 * @param STOREID 店铺ID
	 * @param GOODSID 商品ID
	 */
	public void doCollect(){
		String storeidStr = getPara("STOREID");
		String goodsidsStr = getPara("GOODSID");
		String isSelfsStr = getPara("ISSELF");
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}else if(StrKit.isBlank(goodsidsStr)){
			renderFailed("参数GOODSID不能为空");
			return;
		}
		String[] goodsids,isSelfs;
		if(goodsidsStr.indexOf(",")>=1&&isSelfsStr.indexOf(",")>=1){
			goodsids = goodsidsStr.split(",");
			isSelfs = isSelfsStr.split(",");
		}else{
			goodsids = new String[]{goodsidsStr};
			isSelfs = new String[]{isSelfsStr};
		}
		//批量收藏
		service.doCollect(Integer.valueOf(storeidStr),getCurrentUser().getInt("id"),goodsids,isSelfs);
		renderSuccess("收藏成功");
	}
	
	/**
	 * 用户取消收藏指定商品
	 * @param GOODSID 商品ID
	 */
	public void cancelCollect(){
		String goodsidsStr = getPara("GOODSID");
		if(StrKit.isBlank(goodsidsStr)){
    		renderFailed("参数GOODSID不能为空");
    		return;
		}
		String[] goodsids;
		if(goodsidsStr.indexOf(",")>=1){
			goodsids = goodsidsStr.split(",");
		}else{
			goodsids = new String[]{goodsidsStr};
		}
		//批量取消收藏
		service.cancelCollect(getCurrentUser().getInt("id"),goodsids);
		renderSuccess();
	}
	
	/**
	 * 分页查询用户收藏商品列表
	 * @param STOREID 店铺ID
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void collectionList(){
		String storeidStr = getPara("STOREID");
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}
		Page<Record> page = service.findCollectionByPage(Integer.valueOf(storeidStr),getCurrentUser().getInt("id"),pageNum, pageSize);
		renderSuccess(ResultMap.newInstance()
				.put("PAGENUMBER", page.getPageNumber())
				.put("PAGESIZE", page.getPageSize())
				.put("TOTALPAGE", page.getTotalPage())
				.put("TOTALROW", page.getTotalRow())
				.put("LIST", page.getList()));
	}
	
	/**
	 * 收藏操作
	 * @param FAV  是否取消收藏  false 取消收藏
	 */
	public void setCollect(){
		String fav = getPara("FAV");
		String goodsid = getPara("GOODSID");
		if(StrKit.isBlank(fav)){
    		renderFailed("参数FAV不能为空");
    		return;
		}else if(StrKit.isBlank(goodsid)){
			renderFailed("参数GOODSID不能为空");
			return;
		}
		UserCollection userCollection=new UserCollection().set("userid", Integer.valueOf(getCurrentUser().getInt("id")))
				.set("goodsid", Integer.valueOf(goodsid))
				.set("isCancel", 0)
				.set("createDate", new Date());
		renderSuccess(service.setCollect(userCollection,fav,Integer.valueOf(goodsid),Integer.valueOf(getCurrentUser().getInt("id"))));
	}
	
	/**
	 * 查询用户抵扣券,优惠券，积分，收藏数量
	 */
	public void property() {
		Record collectionNum=service.countCollectionList(getCurrentUser().getInt("id"));
		renderSuccess(collectionNum);
	}
	
	
	
	/**
	 * 查询用户收藏商品列表
	 */
	public void collectionList1(){
		String goodsid=getPara("GOODSID");
		if (!"undefined".equals(goodsid)) {
			List<Record> collectionList2 = service.findCollection(getCurrentUser().getInt("id"),goodsid);
			if(collectionList2.size()>0&&collectionList2!=null){
				renderSuccess(collectionList2);
			}else{
				renderFailed("收藏为空");
			}
			
		}
		
	}
	
	/**
	 * 查询用户收货地址列表
	 */
	public void addressList(){
		List<UserAddress> list = service.findAddress(getCurrentUser().getInt("id"));
		if(list.size()>0&&list!=null){
			renderSuccess(list);
		}else{
			renderFailed("没有收货地址");
		}
		
	}
	
	/**
	 * 增加收货地址
	 * @param LINKNAME 收货人姓名
	 * @param SEX 性别
	 * @param TEL 联系电话，座机或手机号
	 * @param COMMUNITYID 社区ID
	 * @param #BUILDID 楼号ID
	 * @param #UNITID 单元号ID
	 * @param #ROOMID 房间门牌号ID
	 * @param ADDRESS 详细地址
	 * @param ISDEFAULT 是否设置为默认收货地址，1：是，0：否
	 */
	public void addAddress(){
		String linkName = getPara("LINKNAME");
		String tel = getPara("TEL");
		String addressStr = getPara("ADDRESS");
		String isDefaultStr = getPara("ISDEFAULT");
		if(StrKit.isBlank(linkName)){
			renderFailed("收货人姓名不能为空");
			return;
		}else if(linkName.length()>20){
			renderFailed("收货人姓名过长");
			return;
		}else if(StrKit.isBlank(tel)){
			renderFailed("手机号不能为空");
			return;
		}else if(!ValidateKit.Tel(tel)&&!ValidateKit.Mobile(tel)){
			renderFailed("手机号格式错误");
			return;
		}else if(StrKit.isBlank(addressStr)){
			renderFailed("详细地址不能为空");
			return;
		}else if(!StrKit.isBlank(isDefaultStr)&&!isDefaultStr.equals("1")&&!isDefaultStr.equals("0")){
			renderFailed("参数ISDEFAULT错误");
			return;
		}
		int userid = getCurrentUser().getInt("id");
		UserAddress address = new UserAddress()
				.set("userid", userid)
				.set("linkName", linkName)
				.set("tel", tel)
				.set("address",addressStr);
		if(service.addAddress(userid,address,Integer.valueOf(isDefaultStr))){
			renderSuccess(address);
		}else{
			renderFailed("添加收货地址失败");
		}
	}
	
	/**
	 * 删除收货地址
	 * @param ADDRESSID 收货地址ID
	 */
	public void delAddress(){
		String addressidStr = getPara("ADDRESSID");
		if(StrKit.isBlank(addressidStr)){
    		renderFailed("参数ADDRESSID不能为空");
    		return;
		}
		String[] addressids;
		if(addressidStr.indexOf(",")>=1){
			addressids = addressidStr.split(",");
		}else{
			addressids = new String[]{addressidStr};
		}
		//批量删除收货地址
		service.delAddress(getCurrentUser().getInt("id"),addressids);
		
		renderSuccess("删除成功");
	}
	
	/**
	 * 修改收货地址
	 * @param ADDRESSID 收货地址ID
	 * @param LINKNAME 收货人姓名
	 * @param TEL 联系电话，座机或手机号
	 * @param ADDRESS 详细地址
	 * @param ISDEFAULT 是否设置为默认收货地址，1：是，0：否
	 */
	public void updateAddress(){
		String addressidStr = getPara("ADDRESSID");
		String linkName = getPara("LINKNAME");
		String tel = getPara("TEL");
		String addressStr = getPara("ADDRESS");
		String isDefaultStr = getPara("ISDEFAULT");
		if(StrKit.isBlank(addressidStr)){
			renderFailed("参数ADDRESSID不能为空");
			return;
		}else if(StrKit.isBlank(linkName)){
			renderFailed("收货人姓名不能为空");
			return;
		}else if(linkName.length()>20){
			renderFailed("收货人姓名过长");
			return;
		}else if(StrKit.isBlank(tel)){
			renderFailed("联系人电话不能为空");
			return;
		}else if(!ValidateKit.Tel(tel)&&!ValidateKit.Mobile(tel)){
			renderFailed("联系人电话格式错误");
			return;
		}else if(StrKit.isBlank(addressStr)){
			renderFailed("详细地址不能为空");
			return;
		}else if(!StrKit.isBlank(isDefaultStr)&&!isDefaultStr.equals("1")&&!isDefaultStr.equals("0")){
			renderFailed("参数ISDEFAULT错误");
			return;
		}
		int userid = getCurrentUser().getInt("id");
		UserAddress address = new UserAddress()
				.set("id", Integer.valueOf(addressidStr))
				.set("userid", userid)
				.set("linkName", linkName)
				.set("tel", tel)
				.set("address",addressStr);
		if(service.updateAddress(userid,address,Integer.valueOf(isDefaultStr))){
			renderSuccess(address);
		}else{
			renderFailed("更新收货地址失败");
		}
	}
	
	/**
	 * 查询指定ID的收货地址详情
	 * @param ADDRESSID 收货地址ID
	 */
	public void addressDetail(){
		String addressidStr = getPara("ADDRESSID");
		if(StrKit.isBlank(addressidStr)){
    		renderFailed("参数ADDRESSID不能为空");
    		return;
		}
		UserAddress address = service.findAddressById(Integer.valueOf(addressidStr));
		if(address!=null){
			renderSuccess(address);
		}else{
			renderFailed("没有收货地址");
		}
	}

	
	/**
	 * 查询当前登录用户的默认收货地址
	 */
	public void defaultAddress(){
		UserAddress address = service.findDefaultAddressByUser(getCurrentUser().getInt("id"));
		if(address!=null){
			renderSuccess(address);
		}else{
			renderFailed("没有收货地址");
		}
	}
	
	/**
	 * 查询用户服务订单列表
	 */
	public void serviceOrderList(){
		String storeidStr = getPara("STOREID");
		if(StrKit.isBlank(storeidStr)){
    		renderFailed("参数STOREID不能为空");
    		return;
		}
		int flag = getParaToInt("FLAG",0);
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		Page<Record> page = service.findServiceOrderByPage(Integer.valueOf(storeidStr).intValue(),getCurrentUser().getInt("id"),flag,pageNum,pageSize);
		renderSuccess(ResultMap.newInstance()
				.put("PAGENUMBER", page.getPageNumber())
				.put("PAGESIZE", page.getPageSize())
				.put("TOTALPAGE", page.getTotalPage())
				.put("TOTALROW", page.getTotalRow())
				.put("LIST", page.getList()));
		return;
	}
	
	/**
	 * 查询用户实惠币记录
	 */
	public void expenseRecord(){
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		int searchType = getParaToInt("SEARCHTYPE",0);
		Page<Record> page = service.findUserExpenseRecord(pageNum, pageSize, getCurrentUser().getInt("id"),searchType);
		if(page!=null && page.getPageSize()>0){
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", page.getList()));
		}else{
			renderFailed("暂无惠币记录");
		}
		
	}
	
	/**
	 * 查询银行
	 */
	public void queryBankName(){
		List<Record> bank= service.queryBankAll();
		renderSuccess(bank);
	}
	/**
	 * 查询银行
	 */
	public void queryBank(){
		String bankName=getPara("BANKNAME");
		if(StrKit.isBlank(bankName)){
    		renderFailed("参数bankName不能为空");
    		return;
		}
		Record bankNoId = service.queryBank(bankName);
		if(bankNoId==null){
			renderFailed("暂不支持该银行");
		}else{
			renderSuccess(bankNoId);
		}
	}
	
	
	/** 绑定银行卡签约  02
	 * @param custName 持卡人姓名
	 * @param phoneNo 绑定手机号
	 * @param idNo 身份证号
	 * @param cardNo 卡号
	 * @param bankCode 银行代码
	 * @param cardType 1借记卡 2贷记卡
	 * @param authMsg 认证发送的短信验证码
	 * @param isDefault 是否设为默认
	 */
	public void addPayCard(){
		String custName = getPara("custName");
		String phoneNo = getPara("phoneNo");
		String cardNo = getPara("cardNo");
		String bankCode = getPara("bankCode");
		
		String idNo = getPara("idNo");
		String cardType = getPara("cardType");
		String authMsg = getPara("authMsg");
		String isDefault = getPara("isDefault");
		String custType = "02";
		int bankNoId=getParaToInt("bankNoId");
		String bankSite=getPara("bankSite");
		if(StrKit.isBlank(custName)){
    		renderFailed("参数custName不能为空");
    		return;
		}else if(StrKit.isBlank(phoneNo)){
			renderFailed("参数phoneNo不能为空");
    		return;
		}else if(StrKit.isBlank(idNo)){
			renderFailed("参数idNo不能为空");
    		return;
		}else if(StrKit.isBlank(cardNo)){
			renderFailed("参数cardNo不能为空");
    		return;
		}else if(StrKit.isBlank(bankCode)){
			renderFailed("参数bankCode不能为空");
    		return;
		}else if(StrKit.isBlank(cardType)){
			renderFailed("参数cardType不能为空");
    		return;
		}else if(StrKit.isBlank(authMsg)){
			renderFailed("参数authMsg不能为空");
    		return;
		}else if(StrKit.isBlank(isDefault)){
			renderFailed("参数isDefault不能为空");
    		return;
		}else if(bankNoId==0){
			renderFailed("参数bankNoId不能为空");
    		return;
		}else if(StrKit.isBlank(bankSite)){
			renderFailed("参数bankSite不能为空");
    		return;
		}
		Map<String,String> dataMap = new HashMap<String,String>();
		dataMap.put("custName", custName);
		dataMap.put("phoneNo", phoneNo);
		dataMap.put("idNo", idNo);
		dataMap.put("cardNo", cardNo);
		dataMap.put("bankCode", bankCode);
		dataMap.put("cardType", cardType);
		dataMap.put("custType", custType);
		dataMap.put("authMsg", authMsg);
		try {
			Bank bank = service.findBankidByBankName(bankCode);
			if(bank!=null){
				renderFailed("暂不支持该银行");
	    		return;
			}
			Map<String,String> map =SQpay.Contract(dataMap);
			int userid = getCurrentUser().getInt("id");
			//判断结果  执行数据存储
			Card card = new Card()
					.set("userid",  userid)
					.set("custName", map.get("custName"))
					.set("phoneNo", map.get("phoneNo"))
					.set("idNo", map.get("idNo"))
					.set("cardNo", map.get("cardNo"))
//					.set("bankid", bank.get("id"))
					.set("cardType", map.get("cardType"))
					.set("bankNoId", bankNoId)
					.set("bankSite", bankSite);
			if(service.addCard(userid,card,Integer.valueOf(isDefault))){
				renderSuccess(card);
			}else{
				renderFailed("添加银行卡失败");
			}
			renderSuccess(ResultMap.newInstance()
					.put("respCode", map.get("respCode"))
					.put("respMess",map.get("respMess")));
			return;
		} catch (Exception e) {
			renderFailed("绑定银行卡失败");
			return;
		}
		
	}
	/** 绑定银行卡认证   01
	* @param custName 持卡人姓名
	 * @param phoneNo 绑定手机号
	 * @param idNo 身份证号
	 * @param cardNo 卡号
	 * @param bankCode 银行代码
	 * @param cardType 1借记卡 2贷记卡
	 */
	public void addPayCardMsg(){
		String custName = getPara("custName");
		String phoneNo = getPara("phoneNo");
		String cardNo = getPara("cardNo");
		String bankCode = getPara("bankCode");
		String idNo = getPara("idNo");
		String cardType = getPara("cardType");
		String custType = "01";
		if(StrKit.isBlank(custName)){
    		renderFailed("参数custName不能为空");
    		return;
		}else if(StrKit.isBlank(phoneNo)){
			renderFailed("参数phoneNo不能为空");
    		return;
		}else if(StrKit.isBlank(idNo)){
			renderFailed("参数idNo不能为空");
    		return;
		}else if(StrKit.isBlank(cardNo)){
			renderFailed("参数cardNo不能为空");
    		return;
		}else if(StrKit.isBlank(bankCode)){
			renderFailed("参数bankCode不能为空");
    		return;
		}else if(StrKit.isBlank(cardType)){
			renderFailed("参数cardType不能为空");
    		return;
		}
		Map<String,String> dataMap = new HashMap<String,String>();
		dataMap.put("custName", custName);
		dataMap.put("phoneNo", phoneNo);
		dataMap.put("idNo", idNo);
		dataMap.put("cardNo", cardNo);
		dataMap.put("bankCode", bankCode);
		dataMap.put("cardType", cardType);
		dataMap.put("custType", custType);
		try {
			Map<String,String> map =SQpay.Contract(dataMap);
			renderSuccess(ResultMap.newInstance()
					.put("respCode", map.get("respCode"))
					.put("respMess",map.get("respMess")));
			return;
		} catch (Exception e) {
			renderFailed("绑定银行卡失败");
			return;
		}
	}
	/** 查询银行卡是否签约  
	 * @param custName 持卡人姓名
	 * @param phoneNo 绑定手机号
	 * @param idNo 身份证号
	 * @param cardNo 卡号
	 */
	public void queryCardCon(){
		String custName = getPara("custName");
		String phoneNo = getPara("phoneNo");
		String idNo = getPara("idNo");
		String cardNo = getPara("cardNo");
		if(StrKit.isBlank(custName)){
    		renderFailed("参数custName不能为空");
    		return;
		}else if(StrKit.isBlank(phoneNo)){
			renderFailed("参数phoneNo不能为空");
    		return;
		}else if(StrKit.isBlank(idNo)){
			renderFailed("参数idNo不能为空");
    		return;
		}else if(StrKit.isBlank(cardNo)){
			renderFailed("参数cardNo不能为空");
    		return;
		}
		Map<String,String> dataMap = new HashMap<String,String>();
		dataMap.put("custName", custName);
		dataMap.put("phoneNo", phoneNo);
		dataMap.put("idNo", idNo);
		dataMap.put("cardNo", cardNo);
		dataMap.put("payAmount", "0.01");
		try {
			Map<String,String> map =SQpay.querySignResult(dataMap);
			renderSuccess(ResultMap.newInstance()
					.put("respCode", map.get("respCode"))
					.put("respMessage",map.get("respMessage")));
			return;
		} catch (Exception e) {
			renderFailed("绑定银行卡失败");
			return;
		}
	}
	
	/**
	 * 查询银行卡
	 */
	public void queryCard(){
		List<Record> card = service.queryCard(getCurrentUser().getInt("id"));
		if(card==null || card.size()==0){
			renderFailed("没有绑定银行卡");
		}else{
			renderSuccess(card);
		}
	}
	/**
	 * 设为默认
	 */
	public void updateCard(){
		String cardid = getPara("CARDID");
		int userid = getCurrentUser().getInt("id");
		if(service.setDefault(userid,cardid)!=1){
			renderFailed("没有绑定银行卡");
		}else{
			renderSuccess("修改成功");
		}
	}
	/**
	 * 查询用户默认付款卡 
	 */
	public void defaultCard(){
		int userid = getCurrentUser().getInt("id");
		Record card = service.findDefaultCardByUser(userid);
		//  根据bankCode查询银行信息
		if(card==null){
			renderFailed("没有绑定的银行卡");
		}else{
			renderSuccess(card);
		}
	}
	
	/**
	 * 删除银行卡
	 * @param 
	 */
	public void delCard(){
		String cardid = getPara("CARDID");
		String idDefault = getPara("ISDEFAULT","0");
		if(StrKit.isBlank(cardid)){
			renderFailed("参数cardid不能为空");
			return;
		}
		if(service.delcard(getCurrentUser().getInt("id"),cardid,idDefault)){
			renderSuccess("删除成功");
		}else{
			renderFailed("删除失败");
		}
		
	}
	/**
	 * 添加银行卡
	 * @param 
	 */
	public void addCard(){
		String custName = getPara("custName");
		String phoneNo = getPara("phoneNo");
		String cardNo = getPara("cardNo");
		String idNo = getPara("idNo");
		String bankCode = getPara("bankCode");
		String cardType = getPara("cardType");
		String isDefault = getPara("isDefault");
		String province=getPara("province");
		String city=getPara("city");
		String bankSite=getPara("bankSite");
		int bankNoId=getParaToInt("bankNoId");
		if(StrKit.isBlank(custName)){
			renderFailed("参数custName不能为空");
			return;
		}else if(StrKit.isBlank(phoneNo)){
			renderFailed("参数phoneNo不能为空");
			return;
		}else if(StrKit.isBlank(bankCode)){
			renderFailed("参数bankCode不能为空");
			return;
		}else if(StrKit.isBlank(cardNo)){
			renderFailed("参数cardNo不能为空");
			return;
		}else if(StrKit.isBlank(idNo)){
			renderFailed("参数idNo不能为空");
			return;
		}else if(StrKit.isBlank(cardType)){
			renderFailed("参数cardType不能为空");
			return;
		}else if(StrKit.isBlank(province)){
			renderFailed("参数province不能为空");
			return;
		}else if(StrKit.isBlank(city)){
			renderFailed("参数city不能为空");
			return;
		}else if(StrKit.isBlank(bankSite)){
			renderFailed("参数bankSite不能为空");
			return;
		}else if(bankNoId==0){
			renderFailed("参数bankNoId不能为空");
			return;
		}
		int userid = getCurrentUser().getInt("id");
		//查询是否已经添加过 
		Card cards = service.findCardByCardNo(userid,cardNo);
		if(cards!=null){
			renderFailed("已经添加过，请勿重复添加");
			return;
		}
		
		System.out.println(bankCode);
		//根据bankName查询bankid
		Bank bank = service.findBankidByBankName(bankCode);
		Card card = new Card()
						.set("userid", userid)
						.set("custName", custName)
						.set("phoneNo", phoneNo)
						.set("cardNo", cardNo)
						.set("bankid", bank.get("id"))
						.set("idNo", idNo)
						.set("cardType", cardType)
						.set("province", province)
						.set("city", city)
						.set("bankSite", bankSite)
						.set("bankNoId", bankNoId);
		
		if(service.addCard(userid,card,Integer.valueOf(isDefault))){
			renderSuccess(card);
		}else{
			renderFailed("添加银行卡失败");
		}				
	}
	
	/**
	 * 团队列表查询
	 */
	public void team(){
		int userid = getCurrentUser().getInt("id");
		//根据用户查询直接子团队
		List<Record> users = service.findByInviteidOne(userid);
		if(users!=null && users.size()>0){
			for(Record u : users){
				u.set("LEVEL", UserCode.UserLevel.getMap().get(u.getInt("taici")));
				List<Record> userss = service.findByInviteidOne(u.getInt("id"));
				if(users!=null && users.size()>0){
					u.set("invite", userss);
					for(Record us : userss){
						us.set("LEVEL", UserCode.UserLevel.getMap().get(us.getInt("taici")));
					}
				}
			}
			renderSuccess(users);
		}else{
			renderFailed("无被邀请人");
		}
		
		
	}
	
	/**
	 * 查询每日签到记录
	 */
	public void querySignAward()  {
		
	  	//获取用户签到信息
	  	User user=service.findUserInfoById(getCurrentUser().getInt("id"));
	    int signSum=user.getInt("signSum");
	    Date signRecord=user.get("signRecord");
	    //判断今天和昨天有没有签到
	    int isSign=1;
	    Calendar cal1=Calendar.getInstance();//最后签到日期
	    Calendar cal2=Calendar.getInstance();//当前其日期
	    Calendar cal3=Calendar.getInstance();//昨天日期
	    if(signRecord==null){
	    	cal1.setTime(new Date());
	    }else {
	    	cal1.setTime(signRecord);
		}
	    cal1.setTime(signRecord);
	    cal2.setTime(new Date());
	    cal3.add(Calendar.DATE, -1);
	    if (!DateUtils.isSameDay(cal1, cal2)) {
	    	isSign=0;
	    	if (!DateUtils.isSameDay(cal1, cal3)||signSum==8) {
				signSum=0;
			}
		}
	    //更新数据库
	    user.set("signRecord", signRecord).set("signSum", signSum);
	    service.update(user);
	    
	    //查询奖励信息
		Double sppointAward=0.00;
		Double sppointAwardExtra=0.00;
		try {
			sppointAward = SysConfig.getSignSpoint();
			sppointAwardExtra=SysConfig.getSignSpointExtra();
			renderSuccess(ResultMap.newInstance().put("SPPOINTAWARD",sppointAward).put("SPPOINTAWARDEXTRA", sppointAwardExtra).put("SIGNSUM", signSum).put("ISSIGN", isSign));
		} catch (Exception e) {
			renderFailed("签到奖励查询失败");
			return;
		}
		
	}
	
	/**
	 * 签到   TODO
	 */
	public void sign()  {
		
	    //获取已连续签到天数
        User user=service.findUserInfoById(getCurrentUser().getInt("id"));
		int signSum=user.getInt("signSum");
		//获取积分奖励
		Double sppoint=0.00;
		try {
			sppoint = SysConfig.getSignSpoint();
			if (signSum==7) {
				sppoint=sppoint+SysConfig.getSignSpointExtra();
			}
			
		} catch (Exception e) {
			renderFailed("获取签到奖励失败");
			return;
		}
		signSum=signSum+1;
		//奖励用户财富信息并记录表
		String orderNumStore = "QD"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		Record re = new Record();
		re.set("userid", getCurrentUser().getInt("id"))
		.set("type",1)
		.set("flag",8)
		.set("fromOrderNum",orderNumStore)
		.set("data",1)
		.set("describe","签到奖励");
		try {
			if(service.sign(getCurrentUser(),sppoint,re,signSum,1)){
				renderSuccess();
			}else{
				renderFailed("网络繁忙...，请稍后再试");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("网络繁忙...，请稍后再试");
		}
		
	}
	
	/**
	 * 查询是否需要强制修改支付密码
	 */
	public void findFirst(){
		String encrypted=getCurrentUser().getStr("paypassword");
		if (StrKit.isBlank(encrypted)) {
			renderSuccess(0);
		}else {
			renderSuccess(1);
		}
	}
	/**
	 * 支付系统登录
	 * PWD  支付密码
	 */
	public void loginPay(){
		String pwd=getPara("PWD");
		if(StrKit.isBlank(pwd)){
			renderFailed("密码不能为空");
			return;
		}
		String encrypted=getCurrentUser().getStr("paypassword");
		if (encrypted==null) {
			renderFailed("尚未设置支付密码");
			return;
		}
		if (CommonKit.passwordsMatch(pwd,encrypted)) {
			renderSuccess();
		}else {
			renderFailed("支付密码错误");
		}
	}
	/**
	 * 设置支付密码
	 * PWD  登录密码
	 * newPwd  支付密码
	 */
	public void setPayPWD(){
		String pwd=getPara("PWD");
		String newPwd=getPara("NEWPWD");
		if(StrKit.isBlank(pwd)){
			renderFailed("密码不能为空");
			return;
		}else if(StrKit.isBlank(newPwd)){
			renderFailed("新密码不能为空");
			return;
		}
		User user=getCurrentUser();
		if (CommonKit.passwordsMatch(pwd, user.getStr("password"))) {
			if (user.set("paypassword", CommonKit.encryptPassword(newPwd)).update()) {
				renderSuccess("设置成功");
			}else {
				renderFailed("失败，请稍后重试");
			}
		}else {
			renderFailed("登录密码错误");
		}
	}
	/**
	 * 修改支付密码
	 * PWD  旧密码
	 * newPwd  新支付密码
	 */
	public void updatePWD(){
		String pwd=getPara("PWD");
		String newPwd=getPara("NEWPWD");
//		String token=getPara("PAYTOKEN");
//		String isFirst=getPara("ISFIRST");
		if(StrKit.isBlank(pwd)){
			renderFailed("密码不能为空");
			return;
		}else if(StrKit.isBlank(newPwd)){
			renderFailed("新密码不能为空");
			return;
		}
		User user=getCurrentUser();
		if (CommonKit.passwordsMatch(pwd, user.getStr("paypassword"))) {
			if (user.set("paypassword", CommonKit.encryptPassword(newPwd)).update()) {
				renderSuccess("修改成功");
			}else {
				renderFailed("失败，请稍后重试");
			}
		}else {
			renderFailed("旧密码错误");
		}
		
		
	}
	/**
	 * 查询余额
	 */
	public void findMoney(){
		User user=getCurrentUser();
		Double money=user.getDouble("money");
		renderSuccess(money);
		
	}
	/**
	 * orderType  1 充值 2 支付 3提现
	 * 
	 */
	public void createOrder(){
		String orderType=getPara("ORDERTYPE");
		String token=getPara("TOKENP");
		String money=getPara("MONEY");
		if(StrKit.isBlank(orderType)){
			renderFailed("参数ORDERTYPE不能为空");
			return;
		}else if(StrKit.isBlank(token)){
			renderFailed("网络繁忙...，请重新登录");
			return;
		}else if(StrKit.isBlank(money)){
			renderFailed("金额不能为空");
			return;
		}
		
		User user = getCurrentUser();
		String orderid = null;
		if("3".equals(orderType)){
			orderid = "M"+DatetimeKit.getFormatDate("yyyyMMddHHmmss")+CommonKit.randomNum(5);
		}else{
			orderid = "M"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(4);
		}
		Map<String,String> map1 = new HashMap<String,String>();
		map1.put("order_type", orderType);//下单类型  1转入  2在线支付  3 转出 
		map1.put("order_id", orderid);
		map1.put("pay_firmid", user.get("payid")+"");
		map1.put("pay_firmname", user.get("name"));
		map1.put("pay_phone", user.get("phone"));
		
		String isPC = EncryUtils.JudgeIsMoblie(getRequest());
		map1.put("terminal_type", isPC);
		if("1".equals(isPC)){
			map1.put("terminal_num","MAC");
		}else if("2".equals(isPC)){
			map1.put("terminal_num","IMEI");
		}else{
			map1.put("terminal_num","OTHER");
		}
		String ip = EncryUtils.getRealIp(getRequest());
		map1.put("order_ip", ip);
		
		String money1 = new DecimalFormat("0.00").format(Double.parseDouble(money));
		map1.put("order_money",money1);
		Double orderfree =0.00;
		if("1".equals(orderType)||"2".equals(orderType)){
			orderfree  = DoubleKit.mul(PayCode.Parameter.ORDERFREE,Double.parseDouble(money) );
		}
		String format = new DecimalFormat("0.00").format(orderfree);
		map1.put("order_fee",format);
		map1.put("token",token);
		JSONObject js = null;
		try {
			if("3".equals(orderType)){
				js =ZYPay.createOrderE(map1);
			}else{
				js =ZYPay.createOrder(map1);
			}
			
		} catch (Exception e) {
			renderFailed("Base64转换失败");
			return;
		}
		Map<String, Object> resMap =EncryUtils.toMap(js);
		if("000000".equals(resMap.get("result"))){
    		//入金or提现
			JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
			
			//创建订单表
//			Record re = new Record().set("orderid", jsondata.get("order_id"))
//									.set("userid", user.getInt("id"))
//									.set("type", 1)
//									.set("ischeck", 0)
//									.set("money", money1)
//									.set("moneyfree", format)
//									.set("createDate", new Date());
//			if(!Db.save("t_bus_user_pay_orderid", re)){
//				renderFailed("记录订单失败");
//				return;
//			}
			new OrderPayAPIRecord().set("orderNum", orderid)
			.set("payMethod", 3)
			.set("flag", 7)
			.set("userId",getCurrentUser().getInt("id"))
			.set("amount",Double.parseDouble(money))
			.save();
    		renderSuccess(jsondata.get("location_url"));
    	}else{
    		//下单or支付or提现
    		renderFailed("网络繁忙...，请稍后重试");
    		return;
    	}
	}
	/**
	 * 查询充值记录
	 * type  1   入金  2提现
	 */
	public void queryMoneyIn(){
		String type=getPara("TYPE");
		String token=getPara("TOKENP");
		if(StrKit.isBlank(type)){
			renderFailed("参数TYPE不能为空");
			return;
		}else if(StrKit.isBlank(token)){
			renderFailed("网络繁忙...，请重新输入支付密码");
			return;
		}
		int count = Integer.parseInt(type);
		int types = 0;
		if(count == 1){
			types = 1005;
		}else{
			types = 1006;
		}
		Map<String,String> map1 = new HashMap<String,String>();
		map1.put("token", token);
		
		JSONObject js =ZYPay.queryMoneyOrder(map1);
		Map<String, Object> resMap =EncryUtils.toMap(js);
		if("000000".equals(resMap.get("result"))){
    		//入金or提现
			JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
			JSONArray JY = (JSONArray) jsondata.get("DATA");
			JSONArray ja = new JSONArray();
			
			for(int i = 0;i<JY.size();i++){
				JSONObject jsonObject = JY.getJSONObject(i);
				if(JY.getJSONObject(i).get("FUNDTYPEID_SYS").equals(types)){
					ja.add(JY.getJSONObject(i));
				}
			}
    		renderSuccess(ja);
    	}else{
    		//下单or支付or提现
    		renderFailed("网络繁忙...，请稍后重试");
    		return;
    	}
		
		
	}
	/**
	 * 查询充值记录
	 * type 1 充值 2提现
	 */
	public void queryMoneyIn1(){
		String type = getPara("TYPE");
		if(StrKit.isBlank(type)){
			renderFailed("参数TYPE不能为空");
			return;
		}
		List<OrderZ>list= service.queryMoneyIn1(getCurrentUser().getInt("id"),type);
		if (list!=null&&list.size()>0) {
			renderSuccess(list);
		}else {
			renderFailed();
		}
		
	}
	
	/**
	 * 查询余额记录
	 */
	public void queryMoneyRecord(){
		List<Record>list= service.queryMoneyRecord(getCurrentUser().getInt("id"));
		if (list!=null&&list.size()>0) {
			renderSuccess(list);
		}else {
			renderFailed();
		}
	}
	
	
	/**
	 * 查询邀请页面
	 */
	public void queryinvite(){
		
		Record re = service.queryInviteByid(getCurrentUser().getInt("id"));
		if(re!=null){
			//邀请人数
			Long count = re.getLong("count");
			//奖励项目
			Double Spoint;
			try {
				Spoint = SysConfig.getInviteSpoint();
			} catch (Exception e) {
				renderFailed("查询邀请人奖励失败");
				return;
			}
			re.set("name",UserCode.UserInvite.INVITENAME);
			re.set("spoint", Spoint);
//			Double Jkpoint = SysConfig.getInviteJkpoint();
//			Double Jypoint = SysConfig.getInviteJypoint();
			//奖励总值
			//积分
			Double inviteSpoint = DoubleKit.mul(Spoint, count);
			re.set("inviteSpoint", inviteSpoint);
			//抵扣券
//			Double inviteJkpoint = DoubleKit.mul(Jkpoint, count);
			//惠券
//			Double inviteJypoint = DoubleKit.mul(Jypoint, count);
			List<Record> list = service.queryInvite(Spoint);
			if(list!=null&&list.size()>0){
				re.set("list", list);
			}else{
				renderFailed("查询邀请人排行榜失败");
			}
			
			
			renderSuccess(re);
		}else{
			renderFailed("您还未邀请任何人");
		}
	}
	
	
	
	
	/**
	 * 下单状态查询
	 */
	public void orderstate(){
		String token=getPara("PAYTOKEN");
		if(StrKit.isBlank(token)){
			renderFailed("网络繁忙...，请稍后重试");
			return;
		}
		int flag = 0;
		//取出未检查或没结果的所有订单
		List<Record> list = service.findPayOrderIdByuserid(getCurrentUser().getInt("id"));
		if(list!=null&&list.size()>0){
			
			//遍历
			for(Record re : list){
				//查询订单状态
				Map<String,String> map = new HashMap<String,String>();
				map.put("order_id", re.getStr("orderid"));
				map.put("token", token);
				JSONObject js = ZYPay.orderstate(map);
				Map<String, Object> resMap =EncryUtils.toMap(js);
				if("000000".equals(resMap.get("result"))){
		    		//查询成功
					JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
					
					//根据状态码确认是否记录，记录状态，
					try {
						int flags = service.logPay(jsondata,getCurrentUser().getInt("id"),re);
						if(flags==1){
							flag = 1;
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						
					}
					
		    	}
			}
		}
		//无论成功与否，都正常返回，记录失败的下次继续取出处理
		renderSuccess(flag);
	}
	/**
	 *	是否匿名,FLAG
	 * 	星星数,SCORE
	 * 	评价内容,COMMENT
	 * 	订单号 ORDERNUM
	 */
	public void comment(){
		String orderNum = getPara("ORDERNUM");
		String flag=getPara("FLAG");
		String score=getPara("SCORE");
		String comment=getPara("COMMENT");
		String specid = getPara("SPECID");
		if(StrKit.isBlank(flag)){
			renderFailed("参数FLAG不能为空");
			return;
		}else if(StrKit.isBlank(score)){
			renderFailed("参数SCORE不能为空");
			return;
		}else if(StrKit.isBlank(comment)){
			renderFailed("参数COMMENT不能为空");
			return;
		}else if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
			return;
		}else if(StrKit.isBlank(specid)){
			renderFailed("参数SPECID不能为空");
			return;
		}
		String LunBoNum = "C"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		
		Record record = new Record()
				.set("userid", getCurrentUser().getInt("id"))
				.set("orderNum", orderNum)
				.set("eval1", score)
				.set("content", comment)
				.set("specid", specid)
				.set("createDate", new Date())
				.set("LunBoNum", LunBoNum);
		if("1".equals(flag)){
			//如果匿名
			record.set("flag", 1);
		}else{
			record.set("flag", 2);
		}
		String type = orderNum.subSequence(0, 1).toString();
		int count = 0;
		try {
			count = service.addEval(record,type);
		} catch (Exception e) {
			renderFailed("操作失败");
			return;
		}
		if(count==1){
			renderSuccess(LunBoNum);
			return;
		}
	}
	/**
	 * 图片上传
	 */
	@Clear(AuthLoginInterceptor.class)
	public void fileUpload(){
		String LunBoNum = getPara("LUNBONUM");
		if(StrKit.isBlank(LunBoNum)){
			renderFailed("参数LUNBONUM不能为空");
			return;
		}
		UploadFile dat  = getFile("data");
		if(dat!=null){
			String thumbFileName = null;
			String dir = DirKit.getDir(DirKit.COMMENT_IMG);
			try {
				thumbFileName = uploadToFtp(dir,dat);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			Record re = new Record();
			re.set("LunBoNum", LunBoNum)
			  .set("thumb", dir.concat(thumbFileName));
			if(service.saveImageByLunBoNum(re)){
				renderSuccess();
				return;
			}else{
				renderFailed("上传失败");
				return;
			}
		}else{
			renderFailed("上传失败");
		}
		
	}

	

	
	/**
	 * 上传图片至指定FTP目录，并返回重新生成的UUID文件名（含扩展名部分，可直接保存数据库）
	 */
	protected String uploadToFtp(String ftpPath,UploadFile file) throws IOException{
		//获取文件，并上传至FTP根目录下，用UUID重命名
		String fileName = file.getFileName();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = CommonKit.getUUID();
		FTPClientKit.upload(ftpPath, newFileName + extension, file.getFile());
		return newFileName + extension;
	}
	
	/**
	 * 添加商品浏览历史记录
	 */
	public void addHistory() {
		String goodsType= getPara("TYPE");
		String goodsId= getPara("GOODSID");
		String sId=getPara("SID");
		if (StrKit.isBlank(goodsType)) {
			renderFailed("参数TYPE不能为空");
    		return;
		}
		if (StrKit.isBlank(goodsId)) {
			renderFailed("参数GOODSID不能为空");
    		return;
		}
		int userId=getCurrentUser().getInt("id");
		int goodsIdi=Integer.valueOf(goodsId);
		int goodsTypei=Integer.valueOf(goodsType);
		if (goodsTypei==2) {
			if (StrKit.isBlank(sId)) {
				renderFailed("参数SID不能为空");
	    		return;
			}
			
		}
		//判断是否已有记录
		History history= service.queryHistory(userId, goodsIdi, goodsTypei);
		if (history!=null) {
			history.set("createDate", new Date());
			if(service.updateHistory(history)){
				renderSuccess();
			}else {
				renderFailed();
			}
		}else {
			History history1=new History();
			if (goodsTypei==1) {
				history1.set("goodsType", goodsTypei).set("goodsId", goodsIdi).set("userId", userId);
			}else {
				int sIdi=Integer.valueOf(sId);
				history1.set("goodsType", goodsTypei).set("goodsId", goodsIdi).set("userId", userId).set("sId", sIdi);
			}
			
			if (service.addHistory(history1)) {
				renderSuccess(); 
			}else {
				renderFailed();
			}
			
		}
		
	}
	
	/**
	 * 查询用户浏览历史商品
	 */
//	@Clear(AuthLoginInterceptor.class)
	public void history(){
		List<History> history = service.findHistory(getCurrentUser().getInt("id"));
		if(history!=null && history.size()>0){
			List<Record> his=new ArrayList<Record>();
			for(History h:history){
				if (h.getInt("goodsType")==1) {
					Record hi= service.findHistoryDetail(h.getInt("goodsId"));
					if (hi!=null) {
						hi.set("historyId", h.getInt("id"));
						his.add(hi);
					}
				}else {
					Record hii=service.findHistoryExchangeDetail(h.getInt("goodsId"));
					if (hii!=null) {
						hii.set("historyId", h.getInt("id")).set("sId", h.getInt("sId"));
						his.add(hii);
					}
				}
			}
			renderSuccess(his);
		}else{
			renderFailed("您还没有浏览记录");
		}
		
		
	}
	
	/**
	 * 删除浏览记录
	 */
	public void deleHistory() {
		String ids=getPara("IDS");
		if (StrKit.isBlank(ids)) {
			renderFailed("参数异常");
			return;
		}
		String [] idsi=ids.split(",");
		for (int i = 0; i < idsi.length; i++) {
			service.deleHistory(Integer.valueOf(idsi[i]));
		}
		renderSuccess("删除成功");
	}
	
	/**
	 * 查询用户积分变化记录
	 */
	public void valueLog() {
		List<Record> valueLog=service.valueLog(getCurrentUser().getInt("id"));
		if(valueLog!=null&&valueLog.size()>0){
			renderSuccess(valueLog);
			return;
		}else{
			renderFailed("无积分变化记录");
		}
	}
	
	/**
	 * 保存用户反馈
	 */
	public void feedback() {
		String type=getPara("TYPE");
		String context=getPara("CONTEXT");
		String contact=getPara("CONTACT");
		if (StrKit.isBlank(type)) {
			renderFailed("反馈类型不能为空");
			return;
		}
		if (StrKit.isBlank(context)) {
			renderFailed("反馈内容不能为空");
			return;
		}
		String feedbackImgNo = "F"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		
		Record record = new Record()
				.set("userid", getCurrentUser().getInt("id"))
				.set("type", Integer.valueOf(type))
				.set("context", context)
				.set("contact", contact)
				.set("imgNo", feedbackImgNo);
		int count = 0;
		try {
			count = service.addFeedback(record);
		} catch (Exception e) {
			renderFailed("操作失败");
			return;
		}
		if(count==1){
			renderSuccess(feedbackImgNo);
			return;
		}
	}
	
	/**
	 * 反馈图片上传
	 */
	@Before(POST.class)
	@Clear(AuthLoginInterceptor.class)
	public void fileUpload1(){
		UploadFile dat  = getFile("data");
		String feedbackImgNo = getPara("FEEDBACKIMGNO");
		if(StrKit.isBlank(feedbackImgNo)){
			renderFailed("参数FEEDBACKIMGNO不能为空");
			return;
		}
		if(dat!=null){
			String thumbFileName = null;
			String dir = DirKit.getDir(DirKit.FEEDBACK_IMG);
			try {
				thumbFileName = uploadToFtp(dir,dat);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
			Record re = new Record();
			re.set("feedbackImgNo", feedbackImgNo)
			  .set("thumb", dir.concat(thumbFileName));
			if(service.saveFeedbackImageByLunBoNum(re)){
				renderSuccess();
				return;
			}else{
				renderFailed("上传失败");
				return;
			}
		}else{
			renderFailed("上传失败");
		}
		
	}
	
	/**
	 * 兑换电子券
	 */
	public void exchangeEcoupon() {
		String ecoupon=getPara("ECOUPON");
		String scale=getPara("SCALE");
		if (StrKit.isBlank(scale)) {
			renderFailed("兑换比例异常");
			return;
		}
		if (StrKit.isBlank(ecoupon)) {
			renderFailed("可兑换数量不能为0");
			return;
		}
		if (Integer.valueOf(ecoupon)==0) {
			renderFailed("惠券不足");
			return;
		}
		//更改用户财富信息并记录表
		Record re = new Record();
		String orderNumStore = "DH"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		
		re.set("userid", getCurrentUser().getInt("id"))
		.set("type",2)
		.set("flag",10)
		.set("fromOrderNum",orderNumStore)
		.set("data",1)
		.set("describe","兑换电子券");
		
		Double jypoint=(double) (Integer.valueOf(scale)*Integer.valueOf(ecoupon));
		Double ecoupond=(double)Integer.valueOf(ecoupon);
		int count = 0;
		try {
			count = service.updateValue(getCurrentUser(),0.00,0.00,jypoint,ecoupond,0.00,re,2);
			if (count!=1) {
				renderFailed("更改失败");
				return;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("更改失败");
			return;
		}
		//更改用户兑换状态
		User user=getCurrentUser();
		user.set("ecouponState", 1);
		service.update(user);
		renderSuccess("兑换成功");
	}
	
	
	
	/**
	 * 刷新token
	 */
	public void flesh(){
		String token = getPara("TOKEN");
		int count = service.updateToken(token);
		if(count == 1){
			renderSuccess("更新成功");
		}else{
			renderFailed("刷新失败");
		}
	}
	/**
	 * 查找邀请收集ID
	 */
	@Clear(AuthLoginInterceptor.class)
	public void findUserid(){
		String phone = getPara("PHONE");
		Record re = service.findUserByPhone(phone);
		if(re!=null){
			renderSuccess(re.getInt("id")+"");
			return;
		}
		renderFailed("请输入正确的邀请人手机号");
	}
	
	/**
	 * 查询邀请奖励详情
	 */
	public void queryInviteDetail() {
		Record record=service.queryInviteByid(getCurrentUser().getInt("id"));
		if (record!=null) {
			record.set("name",UserCode.UserInvite.INVITENAME);
			Double sppoint=0.00;
			List<Record> logList= service.valueLog(getCurrentUser().getInt("id"));
			for (Record re : logList) {
				if (re.getInt("flag")==6) {
					sppoint+=re.getDouble("sppoint");
				}
			}
			record.set("sppoint", sppoint);
			List<Record>invite=service.findByInviteidOne(getCurrentUser().getInt("id"));
			record.set("invite", invite);
			renderSuccess(record);
		}else{
			renderFailed("您名下无邀请人");
		}
	}
	/**
	 * 获取图形验证码
	 */
	public void findImage(){
		JSONObject js = ZYPay.findImage();
		Map<String, Object> resMap =EncryUtils.toMap(js);
		if("000000".equals(resMap.get("result"))){
    		//查询成功
			JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
			String token = (String)jsondata.get("CAPTCHA_TOKEN");
			Record re = new Record();
			re.set("token", token);
			renderSuccess(re);
    	}else{
    		renderFailed("获取图片失败");
    	}
		
	}
	/**
	 * 获取验证码
	 */
	public void sendResetPayPwdCode(){
		String code = getPara("CODE");
		String phone = getPara("PHONE");
		String token = getPara("TOKENP");
		if(StrKit.isBlank(code)){
			renderFailed("请输入图中数字");
			return;
		}else if(StrKit.isBlank(phone)){
			renderFailed("系统异常");
			return;
		}else if(StrKit.isBlank(token)){
			renderFailed("系统异常");
			return;
		}
		Map<String,String > map = new HashMap<String,String>();
		map.put("phoneNumber", phone);
		map.put("CAPTCHA",code);
		map.put("CAPTCHA_TOKEN", token);
		JSONObject js = ZYPay.getCode(map);
		Map<String, Object> resMap =EncryUtils.toMap(js);
		if("000000".equals(resMap.get("result"))){
    		//查询成功
			JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
			renderSuccess("获取验证码成功");
    	}else{
    		renderFailed("图形验证码不正确");
    	}
	}
	/**
	 * 修改支付密码
	 */
	public void resetPayPwd(){
		String code = getPara("CODE");
		String phone = getPara("PHONE");
		String pwd = getPara("PWD");
		if(StrKit.isBlank(code)){
			renderFailed("请输入验证码");
			return;
		}else if(StrKit.isBlank(phone)){
			renderFailed("网络繁忙...，请稍后重试");
			return;
		}else if(StrKit.isBlank(pwd)){
			renderFailed("请输入密码");
			return;
		}
		Map<String,String > map = new HashMap<String,String>();
		map.put("phoneNumber", phone);
		map.put("pwd", pwd);
		map.put("VERIFYCODE", code);
		map.put("operType", "P");
		
		JSONObject js = ZYPay.changePwd(map);
		logger.info("js>>>>>"+js);
		Map<String, Object> resMap =EncryUtils.toMap(js);
		if("000000".equals(resMap.get("result"))){
    		//查询成功
			JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
			renderSuccess("修改密码成功");
    	}else{
    		renderFailed("修改失败");
    	}
	}
	
	
	/**
	 * 微信登录保存openID
	 */
	@Clear({AuthClientTokenInterceptor.class,AuthLoginInterceptor.class})
	public void wxOpenId(){
		//code
		String code = getPara("CODE");
		//appId
		String appId=PropKit.get("MPWX.AppId");
		//APPSecret
		String appSecret=PropKit.get("MPWX.AppSecret");
		//授权（必填）
		String grant_type = PropKit.get("MPWX.Grant_type");
		//URL
		String requestUrl = PropKit.get("MPWX.RequestUrl");
        //请求参数
        String params = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String data = HttpKit.get(requestUrl+params);
        //解析相应内容（转换成json对象）
        JSONObject  json = JSONObject.fromObject(data);
        //用户的唯一标识（openid）
        String openId =String.valueOf(json.get("openid"));
        //用户此次登录的session_key
        String session_key =String.valueOf(json.get("session_key"));
        //保存到微信表
        Record record=service.FindWxUser(openId);
        if (record==null) {
        	 record=new Record();
             record.set("openid", openId);
             if(service.wxOpenId(record)){
             	renderSuccess(record);
             }else {
     			renderFailed();
     		}
		}else {
			renderSuccess(record);
		}
	}
	
	/**
	 * 保存微信用户信息
	 */
	@Clear(AuthLoginInterceptor.class)
	public void updateUserInfoWx(){
		//手机终端注册号
		String clientid = getPara("SIGNATURE");
		String openId=getPara("OPENID");
		if (StrKit.isBlank(openId)) {
			renderFailed("网络错误");
			return;
		}
		String nickName=getPara("NICKNAME");
		String headimgurl=getPara("HEADIMGURL");
		String city=getPara("CITY");
		String province=getPara("PROVINCE");
		String country=getPara("COUNTRY");
		String sex=getPara("SEX");
		 //保存到微信表
        Record record=service.FindWxUser(openId);
        if(record==null){
        	renderFailed("未找到OPENID");
        	return;
        }
        record.set("openid", openId)
        .set("nickName", nickName)
        .set("headimgurl", headimgurl)
        .set("city", city)
        .set("province", province)
        .set("country", country);
        //判断性别是否存在
        if (!StrKit.isBlank(sex)) {
			int sex1=Integer.valueOf(sex);
			record.set("sex", sex1);
		}
        //判断该openID是否已和用户表绑定
    	if (record.getInt("userid")==0) {
    		//未绑定，返回-1，跳转注册页面
    		if (!service.updateUserInfoWx(record)) {
    			renderFailed("信息更新失败");
			}
        	renderFailed();
		}else {
			//已绑定，直接登录
			 //保存成功后，创建用户与Client之间的session，即登录操作
			String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
	        try {
				if(service.wxLogin(record,sessionid, record.getInt("userid"), clientid)){
					//登录成功后，将sessionid返回
					renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(record.getInt("userid"))));
				}else {
					renderFailed();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				renderFailed("网络错误");
			}
		}
	} 
	
	/**
	 * 根据手机号查询是否存在该用户
	 */
	@Clear(AuthLoginInterceptor.class)
	public void fingUserByPhone(){
		String phone =getPara("PHONE");
		if (StrKit.isBlank(phone)) {
			renderFailed("手机号不能为空");
			return;
		}
		User user=service.findByPhone(phone);
		if (user!=null) {
			renderSuccess();
		}else {
			renderFailed();
		}
	}
	
	/**
	 * 微信登录绑定手机号
	 */
	@Clear(AuthLoginInterceptor.class)
	public void wxToPhone() {
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String code = getPara("CODE");
    	String openId=getPara("OPENID");
		
    	//验证各参数
    	if (StrKit.isBlank(openId)) {
			renderFailed("参数OPENID不能为空");
			return;
		}else if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(!ValidateKit.Mobile(msisdn)){
    		renderFailed("参数PHONE格式不正确");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("参数CODE不能为空");
    		return;
    	}
    	//验证短信验证码
    	String cacheKey = CacheHolder.key(CacheKey.CACHE_REGIST_SMS_VALID_CODE_KEY,clientid,msisdn);
    	if(!CacheHolder.has(cacheKey)){
    		renderFailed("未获取短信验证码或验证码已超时，请重新获取");
    		return;
    	}else if(!CacheHolder.getStr(cacheKey).equals(code)){
    		renderFailed("验证码不正确");
    		return;
    	}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
		//判断手机号是否已注册
    	User user=service.findByPhone(msisdn);
		if(user!=null){
			//如果注册了把手机号和微信关联
    		Record record=service.FindWxUser(openId);
    		record.set("userid", user.getInt("id"));
    		if (service.updateUserInfoWx(record)) {
    			//保存成功后，创建用户与Client之间的session，即登录操作
        		String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
    			if(service.login(sessionid, user.getInt("id"), clientid)){
    				//登录成功后，将sessionid返回
    	    		renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(user.getInt("id"))));
    			}else{
    				renderSuccess();
    			}
        		return;
			}else {
				renderFailed("请重新登录");
			}
    	}
	}
	
	/**
	 * 微信登录，手机号注册新用户
	 */
	@Clear(AuthLoginInterceptor.class)
	public void wxPhone() {
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	String password = getPara("PASSWORD");
    	String code = getPara("CODE");
    	int inviteid = Integer.valueOf(getPara("INVITEID"));
    	String openId=getPara("OPENID");
		
    	//验证各参数
    	if (StrKit.isBlank(openId)) {
			renderFailed("参数OPENID不能为空");
			return;
		}else if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(!ValidateKit.Mobile(msisdn)){
    		renderFailed("参数PHONE格式不正确");
    		return;
    	}else  if(StrKit.isBlank(password)){
    		renderFailed("参数PASSWORD不能为空");
    		return;
    	}else if(ValidateKit.Password_reg(password)){
    		renderFailed("密码只能填写数字、字母、下划线组合");
    		return;
    	}else if(password.length()<6||password.length()>18){
    		renderFailed("请保持密码长度在6-18之间");
    		return;
    	}else if(StrKit.isBlank(code)){
    		renderFailed("参数CODE不能为空");
    		return;
    	}
    	//验证短信验证码
    	String cacheKey = CacheHolder.key(CacheKey.CACHE_REGIST_SMS_VALID_CODE_KEY,clientid,msisdn);
    	if(!CacheHolder.has(cacheKey)){
    		renderFailed("未获取短信验证码或验证码已超时，请重新获取");
    		return;
    	}else if(!CacheHolder.getStr(cacheKey).equals(code)){
    		renderFailed("验证码不正确");
    		return;
    	}
		//移除缓存中的验证码
		CacheHolder.remove(cacheKey);
		//判断手机号是否已注册
    	User user=service.findByPhone(msisdn);
		if(user!=null){
			//如果注册了把手机号和微信关联
    		Record record=service.FindWxUser(openId);
    		record.set("userid", user.getInt("id"));
    		if (service.updateUserInfoWx(record)) {
    			//保存成功后，创建用户与Client之间的session，即登录操作
        		String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
    			if(service.login(sessionid, user.getInt("id"), clientid)){
    				//登录成功后，将sessionid返回
    	    		renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(user.getInt("id"))));
    			}else{
    				renderSuccess();
    			}
        		return;
			}else {
				renderFailed("请重新登录");
			}
    		
    	}else {
    		
    	//如果没有注册，注册会员
    	user = new User()
    			.set("name", msisdn)
    			.set("phone", msisdn)
    			.set("createDate",new Date())
    			.set("password", CommonKit.encryptPassword(password))
    			.set("card", DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS").substring(2))
    			.set("babythday", new Date());
    	if(inviteid!=0){
    		User inviteUser = service.findUserByInviteid(inviteid);
    		int BossThreeid = inviteUser.getInt("toBossThreeId");
    		if(BossThreeid == 0){
    			BossThreeid = 1;
    		}
    		System.out.println(">>>>>>>>>>>>>>>>"+BossThreeid);
    		int BossOneid = 0;
    		if(inviteUser.getInt("toBossOneId")!=null){
    			BossOneid = inviteUser.getInt("toBossOneId");
    		}
    		
    		System.out.println(">>>>>>>>>>>>>>>>"+BossOneid);
    		
    		int BossTwoid = 0;
    		if(inviteUser.getInt("toBossTwoId")!=null){
    			BossTwoid = inviteUser.getInt("toBossTwoId");
    		}
    		System.out.println(">>>>>>>>>>>>>>>>"+BossTwoid);
    		user.set("toBossThreeId", BossThreeid)
    			.set("toBossTwoId", BossTwoid)
    			.set("toBossOneId", BossOneid)
    			.set("inviteid", inviteid);
    	}
    	//支付开户
    	Map<String,String> map = new HashMap<String,String>();
		//开户
		map.put("phoneNumber", msisdn);
		map.put("password", password);
		JSONObject json = ZYPay.regist(map);
		Map<String, Object> resMap = EncryUtils.toMap(json);
    	if("000000".equals(resMap.get("result"))){
    		//开户成功
    		JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
    		//获取支付登录id
    		String payid = jsondata.getString("USERID");
    		user.set("payid", payid).set("isUpdate", "0");
    	}else{
    		user.set("isUpdate", 0);
    		//开户失败TODO
//    		renderFailed(json.toString());
//    		return;
    	}
    	//保存用户信息
    	if(service.save(user)){
    		//查询注册奖励
    		Double regSpoint=0.00;
    		Double regJkpoint=0.00;
    		try {
    			regSpoint = SysConfig.getRegSpoint();//获取注册赠送积分
    			regJkpoint=SysConfig.getRegJkpoint();//获取注册赠送抵扣券
    		} catch (Exception e) {
    			renderFailed("查询注册奖励失败");
    		}
    		//奖励新用户财富信息并记录表
			String orderNumStore1 = "ZC"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
			Record re1 = new Record();
			User user2=service.findByPhone(msisdn);
			re1.set("userid", user2.getInt("id"))
			.set("type",1)
			.set("flag",7)
			.set("fromOrderNum",orderNumStore1)
			.set("data",1)
			.set("describe","注册奖励");
			int count1 = 0;
			try {
				count1 = service.updateValue(user2,regSpoint,regJkpoint,0.00,0.00,0.00,re1,1);
			} catch (Exception e1) {
//				renderFailed("新用户注册操作财富日志表失败");
				renderFailed("网络繁忙...，请稍后重试");
				return;
			}
			
    		//邀请人奖励
    		if(inviteid!=0){
    			Double Spoint = 0.00;
    			try {
    				Spoint = SysConfig.getInviteSpoint();
    			} catch (Exception e) {
    				renderFailed("查询邀请人奖励失败");
    				return;
    			}
    			String orderNumStore = "YQ"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
    			User users = service.findUserByInviteid(inviteid);
    			//奖励用户积分信息    记录表
    			Record re = new Record();
    			re.set("userid", inviteid)
    			.set("type",1)
    			.set("flag",6)
    			.set("fromOrderNum",orderNumStore)
    			.set("type",1)
    			.set("data",1)
    			.set("describe","邀请奖励");
    			int count = 0;
				try {
					count = service.updateSpoint(users,Spoint,re);
				} catch (Exception e) {
//					e.printStackTrace();
//					renderFailed("更改表失败");
					renderFailed("网络繁忙...，请稍后重试");
    				return;
				}
    			
    		}
    		//把新建的用户和微信关联
    		User user1=service.findByPhone(msisdn);
    		Record record1=service.FindWxUser(openId);
    		record1.set("userid", user1.getInt("id"));
    		if (service.updateUserInfoWx(record1)) {
    			//保存成功后，创建用户与Client之间的session，即登录操作
        		String sessionid = CommonKit.getUUID().concat(CommonKit.randomNum(4));
    			if(service.login(sessionid, user.getInt("id"), clientid)){
    				//登录成功后，将sessionid返回
    	    		renderSuccess(ResultMap.newInstance().put(ResultField.FIELD_USER_LOGIN_TOKEN,sessionid).put("USER", service.findUserInfoById(user.getInt("id"))));
    			}else{
    				renderSuccess();
    			}
    			return;
			}else {
				renderFailed("请重新登录");
			}
    		}
    	}
    	renderFailed("注册失败");
	}
	/**
	 * 微信登录绑定手机发送手机验证码
     * @param SIGNATURE 设备识别码
	 * @param PHONE 手机号码
	 */
	@Clear(AuthLoginInterceptor.class)
    public void sendWxPhoneCode(){
		String clientid = getPara("SIGNATURE");
    	String msisdn = getPara("PHONE");
    	if(StrKit.isBlank(clientid)){
    		renderFailed("参数SIGNATURE不能为空");
    		return;
    	}else if(StrKit.isBlank(msisdn)){
    		renderFailed("参数PHONE不能为空");
    		return;
    	}else if(!ValidateKit.Mobile(msisdn)){
    		renderFailed("手机号格式不正确");
    		return;
    	}
    	String randomNum = null;
    	String key = CacheHolder.key(CacheKey.CACHE_REGIST_SMS_VALID_CODE_KEY,clientid,msisdn);
    	//判断缓存中是否已经存在未过期的验证码
    	Object oldNum = CacheHolder.get(key);
		if(oldNum!=null){
			//如果有，则继续使用
			randomNum = String.valueOf(oldNum);
		}else{
			//否则生成新的验证码
			randomNum = CommonKit.randomNum();
		}
		if(SMSKit.sendRegCode(msisdn, randomNum)){
			CacheHolder.cache(key, randomNum, CacheHolder.TIME_FIVE_MINUTE);
			Prop debug = new Prop("realtime.properties",Const.DEFAULT_ENCODING);
			if(debug.getBoolean("debug.sms")){
				//短信接口调试模式时，将短信验证码返回给客户端
				renderSuccess(ResultMap.newInstance().put("CODE",randomNum));
				return;
			}else{
				renderSuccess();
				return;
			}
		}
		renderFailed("验证码发送失败，请重新获取");
    }
	
	/**
	 * 查询可使用的惠券：最近七天得到的惠券不能使用
	 * 查询最近七天的惠券增加数量
	 */
	public void queryViablejypoint() {
		Date createDate=DatetimeKit.StrToDate(DatetimeKit.getPNtime(-7, "yyyy-MM-dd HH:mm:ss")) ;
		Record jypointe=service.queryViablejypoint(getCurrentUser().getInt("id"),createDate);
		if (jypointe!=null) {
			renderSuccess(ResultMap.newInstance().put("jypointe", jypointe.getDouble("viablejypoint")));
		}else {
			renderFailed();
		}
	}
	
	
	/**
	 * 查询惠券转换余额状态
	 */
	public void queryExchangeMoneyState() {
		Record state=service.queryExchangeMoneyState(getCurrentUser().getInt("id"));
		if (state!=null) {
			renderSuccess(state);
		}else {
			renderFailed();
		}
	}
	
	/**
	 * 惠券转换余额
	 */
	public void exchangeMoney() {
		//获取可转换的余额
		String ecoupon=getPara("ECOUPON");
		//获取转换比例
		String scale=getPara("SCALE");
		if (StrKit.isBlank(scale)) {
			renderFailed("兑换比例异常");
			return;
		}
		if (StrKit.isBlank(ecoupon)) {
			renderFailed("可兑换数量不能为0");
			return;
		}
		if (Double.valueOf(ecoupon)==0) {
			renderFailed("惠券不足");
			return;
		}
		//更改用户财富信息并记录表
		Record re = new Record();
		String orderNumStore = "YE"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		
		re.set("userid", getCurrentUser().getInt("id"))
		.set("type",2)
		.set("flag",12)
		.set("fromOrderNum",orderNumStore)
		.set("data",1)
		.set("describe","惠券转换余额");
		
		Double jypoint=Double.valueOf(ecoupon)/Double.valueOf(scale)*100;
		Double ecoupond=Double.valueOf(ecoupon);
	    try {
			if (service.exchangeMoney(getCurrentUser(),jypoint,ecoupond,orderNumStore,re,2)) {
				renderSuccess();
			}else {
				renderFailed("网络繁忙...，请稍后再试");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("网络繁忙...，请稍后再试1");
		} 
	}
	
	/**
	 * 查询用户惠券转余额记录
	 */
	public void couponToMoneyLog() {
		List<Record> valueLog=service.couponToMoneyLog(getCurrentUser().getInt("id"));
		if(valueLog!=null&&valueLog.size()>0){
			renderSuccess(valueLog);
			return;
		}else{
			renderFailed("无转换记录");
		}
	}
	
	/**
	 * 发放充值奖励
	 */
	public void rechargeAward() {
		//获取参数
		String token=getPara("TOKENP");
		if (StrKit.isBlank(token)) {
			renderFailed("网络错误：请重新登录");
			return;
		}
		//查询充值奖励
		Double ra=0.00;
		try {
			ra=SysConfig.getRechargeAward();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			renderFailed("获取充值奖励失败");
		}
		//查询为领取的充值订单
		List<Record> rechargeOrder=service.queryRechargeOrder(getCurrentUser().getInt("id"));
		if (rechargeOrder==null||rechargeOrder.size()==0) {
			renderFailed("暂无未领取的奖励");
			return;
		}
		//遍历查询订单状态
		for (Record record : rechargeOrder) {
			Map<String,String> map = new HashMap<String,String>();
			map.put("order_id", record.getStr("orderNum"));
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>订单号"+record.getStr("orderNum"));
			map.put("token", token);
			JSONObject js = ZYPay.orderstate(map);
			Map<String, Object> resMap =EncryUtils.toMap(js);
			if("000000".equals(resMap.get("result"))){
	    		//查询成功
				JSONObject jsondata = JSONObject.fromObject(resMap.get("data"));
				if(jsondata.get("order_type").equals("1")&&jsondata.get("order_status").equals("S")){
					//更新用户积分并记录
					Record re = new Record();
					String orderNumStore = "CZ"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
					
					re.set("userid", getCurrentUser().getInt("id"))
					.set("type",1)
					.set("flag",14)
					.set("fromOrderNum",orderNumStore)
					.set("data",1)
					.set("describe","充值奖励积分");
					try {
						if(service.rechargeAward(record.getStr("orderNum"),getCurrentUser(),ra,re,1)){
						}else {
							renderFailed();
							return;
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						renderFailed();
						return;
					}
				}
	    	}
		}
		renderSuccess();
	}
	
	/**
	 * 微信公众号获取openID
	 */
	public void publicOpenId(){
		//code
		String code = getPara("CODE");
		//appId
		String appId=PropKit.get("PWXPAY.appid");
		//APPSecret
		String appSecret=PropKit.get("PMPWX.AppSecret");
		//授权（必填）
		String grant_type = PropKit.get("MPWX.Grant_type");
		//URL
		String requestUrl = PropKit.get("PWXPAY.openid");
        //请求参数
        String params = "appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String data = HttpKit.get(requestUrl+params);
        //解析相应内容（转换成json对象）
        JSONObject  json = JSONObject.fromObject(data);
        //用户的唯一标识（openid）
        String openId =String.valueOf(json.get("openid"));
        System.out.println("获取微信授权信息"+json);
        //用户此次登录的session_key
//        String session_key =String.valueOf(json.get("session_key"));
        //保存到微信表
//        Record record=service.FindWxUser(openId);
//        if (record==null) {
//        	 record=new Record();
//             record.set("openid", openId);
//             if(service.wxOpenId(record)){
//             	renderSuccess(record);
//             }else {
//     			renderFailed();
//     		}
//		}else {
//			renderSuccess(record);
//		}
        String access_token =String.valueOf(json.get("ACCESS_TOKEN"));
        setSessionAttr("ACCESS_TOKEN", access_token);
        renderSuccess(openId);
	}
	/**
	 * 显示免单团购订单
	 */
	public void freeOrder(){
		List<OrderG> freeOrder = service.freeOrder(getCurrentUser());
		if ( freeOrder!=null && freeOrder.size()>0 ){
			Collections.sort(freeOrder,new Comparator<OrderG>() {

				@Override
				public int compare(OrderG o1, OrderG o2) {
					long l1 = DatetimeKit.StrToDate(o1.getTimestamp("payDate").toString()).getTime();
					long l2 = DatetimeKit.StrToDate(o2.getTimestamp("payDate").toString()).getTime();
					long result = l1-l2;
					if ( result>0 ){
						return -1;
					} else {
						return 1;
					}
				}
			});
			renderSuccess(freeOrder);
		} else {
			renderSuccess();
		}
	}
	/**
	 * 提现
	 */
	public void giveOut(){
		String money = getPara("MONEY");
		if ( StrKit.isBlank(money) ){
			render("金额不能为空");
			return;
		}else {
			User user = getCurrentUser();
			try {
				service.giveOut(user,money);
				renderSuccess();
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e.getMessage());
				renderFailed("网络异常，请稍后再试");
			}
		}
	}
	/**
	 * 进入视频房间检查密码
	 *  ID 0  设置密码    其他  检查密码
	 *  
	 */
	public void goRoom(){
		String id = getPara("ID");
		String pwd = getPara("PWD");
		if ( StrKit.isBlank(id) ){
			render("房间号不能为空");
			return;
		}else if ( pwd.length()!=6 ){
			render("长度不为6");
			return;
		} else if ( StrKit.isBlank(pwd) ){
			render("房间密码不能为空");
			return;
		}else {
			if (Integer.parseInt(id)==0){
				//设置密码
				User user = getCurrentUser();
				if (user.set("roomPwd",Integer.parseInt(pwd)).update())
					renderSuccess();
				else 
					renderFailed("设置密码失败");
			}else {
				User user = User.me().findById(id);
				if (user != null && user.getInt("roomPwd") == Integer.parseInt(pwd))
					renderSuccess();
				else 
					renderFailed("房间号或密码错误");
			}
			
		}
	}
	
	
	/**
	 * 未登录时为你推荐
	 */
	@Clear(AuthLoginInterceptor.class)
	public void recommend(){
		//按照商品浏览量推荐
		User user = null;
		List<Record> list = service.recommend(user);
		if ( list != null && list.size() > 0){
			renderSuccess(list);
		}else{
			renderFailed("暂无推荐");
		} 
			
	}
	/**
	 * 登陆以后为你推荐
	 */
	public void recommendLogining(){
		//按照商品
		List<Record> list = service.recommend(getCurrentUser());
		if ( list != null && list.size() > 0){
			renderSuccess(list);
		}else{
			renderFailed("暂无推荐");
		}
	}
	
}
